# -*- coding: UTF-8 -*-
"""
@author: zec
"""

import re
import tkinter as tk
from tkinter import scrolledtext
 
style={
    'ExpBtn':'#90EE90', #替换表达式
    'OtherBtn':'#87CEFA',   #辅助按键
    'FefreshBtn':"#FFAA50",  #刷新按钮
}

class TextReplaceTool:
    win = tk.Tk() 
    inputFrame = None
    inputLfList = list() 
    inputStList = list() 
    resultSt = None
    ruleSt = None

    def __init__(self,defaultInputCount=2):
        #grid = tk.Grid(win) #grid布局 最外层用grid布局2*2
        self.initInput(defaultInputCount) #grid第1行第1列：输入框
        self.initResult() #grid第1行第2列：结果
        self.initRule() #grid第2行第1列：规则
        self.initButton() # grid第2行第2列：功能按钮

    def initInput(self,count):
        # 默认初始化输入框
        if self.inputFrame == None:
            inF = tk.Frame(self.win)
            inF.grid(row=0, column=0,sticky=tk.W)   
            self.inputFrame = inF
        for i in range(count):
            self.addInputLabFrame()

    # 增加输入框
    def addInputLabFrame(self):        
        inputLfListSize = len(self.inputLfList)
        strNum = str(inputLfListSize+1)
        lf = tk.LabelFrame(self.inputFrame,text="输入-"+strNum)
        st = scrolledtext.ScrolledText(lf,width=40,height=40)
        st.pack()
        tk.Button(lf,text="原值[S"+strNum+"]",command=self.btFunction('S'+strNum),bg=style['ExpBtn']).pack(side=tk.LEFT)
        tk.Button(lf,text="驼峰[C"+strNum+"]",command=self.btFunction('C'+strNum),bg=style['ExpBtn']).pack(side=tk.LEFT)
        tk.Button(lf,text="反驼峰[UnC"+strNum+"]",command=self.btFunction('UnC'+strNum),bg=style['ExpBtn']).pack(side=tk.LEFT)
        tk.Button(lf,text="大写[U"+strNum+"]",command=self.btFunction('U'+strNum),bg=style['ExpBtn']).pack(side=tk.LEFT)
        tk.Button(lf,text="小写[L"+strNum+"]",command=self.btFunction('L'+strNum),bg=style['ExpBtn']).pack(side=tk.LEFT)
        lf.pack(side=tk.LEFT) 
        self.inputLfList.append(lf)
        self.inputStList.append(st)

    def initResult(self):
        # 结果
        result_lf = tk.LabelFrame(self.win,text="结果")
        result_st = scrolledtext.ScrolledText(result_lf,width=80,height=40)
        result_st.pack()
        result_lf.grid(row=0, column=1,sticky=tk.NSEW)
        self.resultSt = result_st

    def initRule(self):
        # 规则
        rule_lf = tk.LabelFrame(self.win,text="规则模板")
        rule_st = scrolledtext.ScrolledText(rule_lf,height=10)
        rule_st.pack(fill=tk.BOTH)
        rule_lf.grid(row=1, column=0,sticky=tk.NSEW)
        self.ruleSt = rule_st

    def initButton(self):
        #按钮
        funcBtn_lf = tk.LabelFrame(self.win,text="功能")
        tk.Button(funcBtn_lf,text="刷新结果",command=self.refreshResult,bg=style['FefreshBtn']).pack(side=tk.LEFT)
        tk.Button(funcBtn_lf,text="增加输入栏",command=self.addInputLabFrame,bg=style['OtherBtn']).pack(side=tk.LEFT)
        tk.Button(funcBtn_lf,text="减少输入栏",command=self.reduceInputLabFrame,bg=style['OtherBtn']).pack(side=tk.LEFT)
        funcBtn_lf.grid(row=1, column=1,sticky=tk.NW)

    def mainloop(self):
        self.win.mainloop()

    # 普通按钮
    def btFunction(self,strNum):
        def wrapper():
            self.ruleSt.insert('insert','#{'+strNum+'}')
        return wrapper

    # 减少输入框
    def reduceInputLabFrame(self):
        self.inputStList.pop()
        lastInputLf = self.inputLfList.pop()
        lastInputLf.pack_forget()

    # 刷新结果
    def refreshResult(self):
        resStr = ""
        ruleStr = self.ruleSt.get(1.0,tk.END)

        inputTextList = [0 for i in range(len(self.inputStList))]
        maxLen = 0
        index = 0
        for item in self.inputStList:
            curText = item.get(1.0,tk.END)
            curTextLineList = curText.strip().split("\n")
            inputTextList[index] = curTextLineList
            currLineLen = len(curTextLineList)
            if currLineLen > maxLen:
                maxLen = currLineLen
            index += 1
           
        j = 0 #依次生成结果的每一行
        while j < maxLen:
            sfIndex = 0 
            resLineStr = ruleStr
            for item in inputTextList: #依次循环输入框的内容，当输入框内的行数大于当前结果行，就进行替换
                btnIdNum = str(sfIndex+1)
                repStrS = '#{S'+btnIdNum+'}'
                repStrC = '#{C'+ btnIdNum + '}'
                repStrUnC = '#{UnC'+ btnIdNum + '}'
                repStrU = '#{U'+ btnIdNum + '}'
                repStrL = '#{L'+ btnIdNum + '}'
                sfIndex += 1
                
                itemJ_Str = ''
                if len(item) > j:
                    itemJ_Str = str(item[j])
                resLineStr = resLineStr.replace(repStrS,itemJ_Str)
                resLineStr = resLineStr.replace(repStrC,re.sub('_[a-z]',lambda x:x.group().replace('_','').upper(), itemJ_Str.lower()))
                resLineStr = resLineStr.replace(repStrUnC,re.sub('[A-Z]',lambda x:('_'+x.group()),itemJ_Str).upper())
                resLineStr = resLineStr.replace(repStrU,itemJ_Str.upper())
                resLineStr = resLineStr.replace(repStrL,itemJ_Str.lower())
            resStr += resLineStr
            j += 1
        self.resultSt.delete(1.0,tk.END)
        self.resultSt.insert(1.0,resStr)
    
if __name__ == '__main__':
    _DefaultInputCount = 2
    trt = TextReplaceTool(_DefaultInputCount)
    trt.mainloop()